package cn.tedu.lucky.draw.server.service.impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.common.enums.ErrorEnum;
import cn.tedu.lucky.draw.server.common.handler.DrawException;
import cn.tedu.lucky.draw.server.protocol.po.ActivityRule;
import cn.tedu.lucky.draw.server.protocol.po.Rule;
import cn.tedu.lucky.draw.server.repository.ActivityRuleRepository;
import cn.tedu.lucky.draw.server.repository.RuleRepository;
import cn.tedu.lucky.draw.server.service.IActivityRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityRuleServiceImpl implements IActivityRuleService {

    @Autowired
    private ActivityRuleRepository repository;

    @Autowired
    private RuleRepository ruleRepository;

    @Override
    public List<Rule> findAllByActivityId(Long id) {
        //需要获取到关联对象
        List<ActivityRule> activityRuleList = repository.findByActivityId(id);
        List<Long> ruleIds = activityRuleList.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        return ruleRepository.findAllById(ruleIds);
    }

    @Override
    public List<Rule> findNoBindRuleByActivityId(Long id) {
        List<ActivityRule> activityRuleList = repository.findByActivityId(id);
        List<Long> excludedIds = activityRuleList.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());
        if (excludedIds.isEmpty()){
            return ruleRepository.findByStatus(status);
        }
        //排除已绑定的IDS以及被禁用活动规则
        return ruleRepository.findByIdNotInAndStatus(excludedIds, status);
    }

    @Override
    public void saveAll(List<ActivityRule> activityRuleList) {
        List<ActivityRule> activityRules = repository.saveAll(activityRuleList);
        if (activityRules.isEmpty()) {
            throw new DrawException(ErrorEnum.SYSTEM_ERROR);
        }
    }
}
